import * as Guid from './guid'

/**
 * 元素的数据store
 * 这些数据不直接应用在元素上
 * 例如：事件listeners就存在这里
 */
const elData = {}

/**
 * 用来存储元素guid的唯一的属性名
 * @type {string}
 * @constant
 * @private
 */
const elIdAttr = 'vdata' + (new Date()).getTime()


/**
 * 返回元素存储的数据
 * @param {*} el
 */
export function getData (el) {
  let id = el[elIdAttr]

  if (!id) {
    id = el[elIdAttr] = Guid.newGUID()
  }

  if (!elData[id]) {
    elData[id] = {}
  }

  return elData[id]
}

// 是否有数据
export function hasData (el) {
  const id = el[elIdAttr]

  if (!id) {
    return false
  }

  return !!Object.getOwnPropertyNames(elData[id]).length
}

/**
 * 删除数据
 * @param {*} el
 */
export function removeData (el) {
  const id = el[elIdAttr]

  if (!id) {
    return
  }

  delete elData[id]

  try {
    delete el[elIdAttr]
  } catch (e) {
    if (el.removeAttribute) {
      el.removeAttribute(elIdAttr)
    } else {
      el[elIdAttr] = null
    }
  }
}
